<?php
require_once 'util/CookieUtil.php';
require_once __SITEPATH__.'/public/ucenter/config.inc.php';
require_once __SITEPATH__.'/public/uc_client/client.php';
// require_once __SITEPATH__.'/public/Solr/Service.php';

class BaseController extends Zend_Controller_Action{
	protected $orm;
	protected $sysConfig;
	protected $userInfo = array();
	protected static $solr;
	protected static $soConfig;
	
	public function init() {
		try {
			$this->orm = ORM::getInstance();
			
			
			//读取配置文件
			$this->sysConfig = require_once __SITEPATH__ . '/application/configs/sysConfig.php';
			
			//设置模版路径
        	$this->view->setScriptPath(__SITEPATH__.'/template/default/');
			
			$this->view->assign(array(
				'controller_name'	=> $this->getRequest()->getControllerName()
			));
			$this->_init();
			
		}catch(Exception $e) {
			$this->toErrorLogs($e);
			$this->_forward('index','error',null,array('status'=>500,'error_obj'=>$e));
		}
	}
	
	//JS返回信息提示
	protected function alert_back($msg){
		$this->view->assign(array(
			'message'		=> $msg,
			'js'			=> 'history.back();'
		));
		echo $this->view->render('inc/alert.htm');
		exit;
	}
	
	//JS返回信息提示并跳转
	protected function alert_go($msg,$url){
		$this->view->assign(array(
			'message'		=> $msg,
			'js'			=> "location.href='$url';"
		));
		echo $this->view->render('inc/alert.htm');
		exit;
	}
	
	//JS返回信息提示确认关闭
	protected function alert_close($msg){
		$this->view->assign(array(
			'message'		=> $msg,
			'js'			=> "window.close();"
		));
		echo $this->view->render('inc/alert.htm');
		exit;
	}
	
	//写入错误日志
	protected function toErrorLogs($e) {
		file_put_contents(__SITEPATH__ . '/logs/' . date('Y-m') . '_' . $this->sysConfig['default']['log_file'],"#############################  " . date('Y-m-d H:i:s') . "  #############################\n" . $e . "\n\n\n",FILE_APPEND);
	}
	
	//用户登陆校验
	protected function checkuser($message){
		if(empty($this->userInfo)){
			$this->alert_go($message, "/member/login");
		}
	}
	
	//返回category分类数组
	protected function categoryarray(){
		$categoryarray = $this->orm->createDAO("_wenda_category")->select("t_cate_id,t_cate_name,t_cate_pid,t_cate_path");
		$categoryarray = $categoryarray->get();
		return $categoryarray;
	}
	
	protected function time_tran($the_time){
	    $now_time = date("Y-m-d H:i:s");
	    $now_time = strtotime($now_time);
	    $show_time = strtotime($the_time);
	    $dur = $now_time - $show_time;
	    if($dur < 60){
	    	return $dur.'秒前';
	    }else{
		    if($dur < 3600){
		     	return floor($dur/60).'分钟前';
		    }else{
			    if($dur < 86400){
			      	return floor($dur/3600).'小时前';
			    }else{
			      	if($dur < 259200){//3天内
			       		return floor($dur/86400).'天前';
			      	}else{
			       		return $the_time;
			      	}
			    }
		    }
	   	}
	}
	
	protected function _init(){}
	
	/**
	 * 声望加减 记录保存
	 * @param int $uid 用户ID
	 * @param string $action 动作类型：ask，answer，best_answer，agree_question，agree_answer，follow_question，follow_user，against_question，against_answer，del_question，del_answer
	 * @param int $aid 表态ID：action_id	赞或踩
	 * @param int $fid	关注ID：follow_id	关注（主题/问题/用户）
	 * @param int $wid 问题ID ：wd_id		（提/回答）问题
	 * @return string
	 */
	protected function integral_rule($uid, $action, $aid=0, $fid=0, $wid=0) {
		try {
			$ruleDAO = $this->orm->createDAO('_integral_rule')->findAction($action)->get();
			if($ruleDAO){
				$userDAO = $this->orm->createDAO('_users_info')->findUser_id($uid);
				$userDAO->integral += $ruleDAO[0]['integral'];
				$userDAO->reputation += $ruleDAO[0]['reputation'];
				$userDAO->save();
				
				$rulelogDAO = $this->orm->createDAO('_integral_rule_log');
				$rulelogDAO->uid = $uid;
				$rulelogDAO->rid = $ruleDAO[0]['rid'];
				$rulelogDAO->aid = $aid;
				$rulelogDAO->fid = $fid;
				$rulelogDAO->wid = $wid;
				$rulelogDAO->integral = $ruleDAO[0]['integral'];
				$rulelogDAO->reputation = $ruleDAO[0]['reputation'];
				$rulelogDAO->dateline = time();
				$rlid = $rulelogDAO->save();
				return $rlid;
			}
		}catch(Exception $e) {
			$this->toErrorLogs($e);
			$this->alert_back(addslashes($e->getMessage()));
		}
	}
	
	/**
	 * 验证是否已关注
	 * @param int $uid 用户ID
	 * @param int $followed_id 目标ID
	 * @param int $followed_type 关注类型：1，话题；2，问题；3，用户
	 * @return boolean
	 */
	protected function check_follow($uid, $followed_id, $followed_type){
		try {
			if($uid && $followed_id && $followed_type){
				$user_followDAO = $this->orm->createDAO('_users_follow');
				$user_followDAO->findUser_id($uid);
				$user_followDAO->findFollowed_id($followed_id);
				$user_followDAO->findFollowed_type($followed_type);
				$user_follow = $user_followDAO->get();
				if($user_follow){
					return true;
				}else{
					return false;
				}
			} else {
				return false;
				//$this->alert_back('数据不能为空！');
			}
		}catch(Exception $e) {
			$this->toErrorLogs($e);
			$this->alert_back(addslashes($e->getMessage()));
		}
	}
	
	/**
	 *  用户回答的问题
	 * @param int $uid 用户ID
	 * @param int $limit 返回的结果数量
	 * @return multitype:
	 */
	protected function getReplyByUserid($uid, $limit = 5){
		try {
			$wenda_replyDAO = $this->orm->createDAO('_wenda_reply')->alias('r');
			$wenda_infoDAO = $wenda_replyDAO ->with_wenda_info(array('wd_reply_wid'=>'wd_id'))->alias('w');
			$wenda_infoDAO ->select('w.wd_id, w.wd_title, w.wd_agree_count, w.wd_view_volume, w.wd_focus_count, w.wd_answer_count, w.wd_tag, w.wd_datetime, r.wd_reply_uid');
			$wenda_replyDAO ->findWd_reply_uid($uid);
			$wenda_replyDAO ->selectLimit = " order by wd_reply_datetime desc limit $limit";
			$wenda_reply = $wenda_replyDAO->get();
			return $wenda_reply;
		}catch(Exception $e) {
			$this->toErrorLogs($e);
			$this->alert_back(addslashes($e->getMessage()));
		}
	}
	
	/**
	 * 热门用户
	 * @param int $limit
	 * @return multitype:
	 */
	protected function getHotUsers($limit = 5){
		$user_infoDAO = $this->orm->createDAO('_users_info')->alias('u');
		$user_infoDAO ->select('u.user_id, u.user_name, u.real_name, u.reputation, u.agree_count, u.answer_count');
		$user_infoDAO ->selectLimit = " group by u.user_id order by u.reputation desc limit $limit";
		$user_info = $user_infoDAO->get();
		return $user_info;
	}
	
	/**
	 * 返回用户的擅长领域
	 * @param int $uid
	 */
	protected function getUserExpertise($uid, $limit = 5){
		try {
			$wenda_replyDAO = $this->orm->createDAO('_wenda_reply')->alias('r');
			$wenda_infoDAO = $wenda_replyDAO ->with_wenda_info(array('wd_reply_wid'=>'wd_id'))->alias('w');
			$wenda_categoryDAO = $wenda_infoDAO ->with_wenda_category(array('wd_cate_id'=>'t_cate_id'))->alias('c');
			$wenda_infoDAO ->select('w.wd_id, r.wd_reply_uid, c.t_cate_id, c.t_cate_name, count(c.t_cate_id) as c_count');
			$wenda_replyDAO ->findWd_reply_uid($uid);
			$wenda_replyDAO ->selectLimit = " group by c.t_cate_id order by c_count desc limit $limit";
			$wenda_reply = $wenda_replyDAO->get();
			return $wenda_reply;
		}catch(Exception $e) {
			$this->toErrorLogs($e);
			$this->alert_back(addslashes($e->getMessage()));
		}
	}
	
	/**
	 * 验证是否为专家，并返回所在专家分类的信息
	 * @param int $uid
	 */
	protected function check_expert($uid){
		try {
			$user_expertDAO = $this->orm->createDAO('_users_expert')->alias('ue');
			$user_expertDAO->findUser_id($uid);
			$user_expertDAO ->with_users_info(array('user_id'=>'user_id'), 'inner')->alias('u');
			$user_expertDAO ->with_wenda_category(array('cate_id'=>'t_cate_id'), 'inner')->alias('c');
			$user_expertDAO ->select('ue.suggest, ue.datetime, u.user_id, u.user_name, u.real_name, c.t_cate_name, c.t_cate_id');
			$result = $user_expertDAO->get();
			return $result;
		}catch(Exception $e) {
			$this->toErrorLogs($e);
			$this->alert_back(addslashes($e->getMessage()));
		}
	}
	
	//获取solr查询对象
	protected static function getSolrInstance() {
		if(!isset(self::$solr)) {
			self::$soConfig = require_once __SITEPATH__ . '/application/configs/soConfig.php';
			
			self::$soConfig['navigator_field'] = unserialize(self::$soConfig['navigator_field']);
			self::$soConfig['result_field'] = unserialize(self::$soConfig['result_field']);
			self::$soConfig['result_setting'] = unserialize(self::$soConfig['result_setting']);
			
			self::$solr = new Apache_Solr_Service(self::$soConfig['server_ip'],self::$soConfig['server_port'],self::$soConfig['server_root_path']);
		}
	}
	
	//相关主题
	protected function relateTopic($keywords) {
		try {
			$params = array(
				'record'		=> 'true',
				'facet' 		=> 'false',
				'hl'			=> 'false',
			);
			
			self::getSolrInstance();
			
			$keywords = preg_replace('/\s+(OR|AND)\s+/su',' ',$keywords);
			$keywords = str_replace(array('(',')','+','-'),'',$keywords);
			$keywords = preg_replace('/\s+/',' ',$keywords);
			
			$relateTopic = self::$solr->search("( $keywords ) AND entity_type:topic",0,5,$params);
			
			$this->view->assign(array(
				'relateTopic'		=> $relateTopic->response->docs
			));
		}catch(Apache_Solr_Exception $e) {
			$this->view->assign(array(
				'relateTopic'		=> array()
			));
			$this->toErrorLogs($e);
		}catch(Exception $e) {
			$this->toErrorLogs($e);
			$this->_forward('index','error',null,array('status'=>500,'error_obj'=>$e));
		}
	}
	
	//相关问题
	protected function relateWenda($keywords,$id = 0) {
		try {
			$params = array(
				'record'		=> 'true',
				'facet' 		=> 'false',
				'hl'			=> 'false',
			);
			
			self::getSolrInstance();
			
			$keywords = preg_replace('/\s+(OR|AND)\s+/su',' ',$keywords);
			$keywords = str_replace(array('(',')','+','-'),'',$keywords);
			$keywords = preg_replace('/\s+/',' ',$keywords);
			
			$query = "( $keywords ) AND entity_type:wenda";
			if($id > 0) {
				$query = "( $query ) NOT id:wenda_{$id}";
			}
			
			$relateWenda = self::$solr->search($query,0,5,$params);
			
			$this->view->assign(array(
				'relateWenda'		=> $relateWenda->response->docs
			));
		}catch(Apache_Solr_Exception $e) {
			$this->view->assign(array(
				'relateWenda'		=> array()
			));
			$this->toErrorLogs($e);
		}catch(Exception $e) {
			$this->toErrorLogs($e);
			$this->_forward('index','error',null,array('status'=>500,'error_obj'=>$e));
		}
	}
	
	//热点主题
	protected function hotTopic() {
		try {
			$params = array(
				'record'		=> 'true',
				'facet' 		=> 'false',
				'hl'			=> 'false',
			);
			
			self::getSolrInstance();
			
			$keywords = strtolower(implode(' ',$this->hotSearchWords()));
			$keywords = preg_replace('/\s+(OR|AND)\s+/su',' ',$keywords);
			$keywords = trim(str_replace(array('(',')','+','-','[',']','00:00z'),'',$keywords));
			
			$keywords = preg_replace('/\s+/',' ',$keywords);
			if($keywords != '') {
				$hotTopic = self::$solr->search("( $keywords ) AND entity_type:topic",0,5,$params);
			}else {
				$hotTopic = self::$solr->search("entity_type:topic",0,5,$params);
			}
			
			$this->view->assign(array(
				'hotTopic'		=> $hotTopic->response->docs
			));
		}catch(Apache_Solr_Exception $e) {
			$this->view->assign(array(
				'hotTopic'		=> array()
			));
			
			$this->toErrorLogs($e);
		}catch(Exception $e) {
			$this->toErrorLogs($e);
			$this->_forward('index','error',null,array('status'=>500,'error_obj'=>$e));
		}
	}
	
	//热搜词
	protected function hotSearchWords() {
		try {
			self::getSolrInstance();
			
			$url['host_port'] = self::$soConfig['server_ip'] . ":" . self::$soConfig['server_port'];
			$url['path'] = trim(self::$soConfig['server_root_path'],'/');
			
			$url = 'http://' . implode('/',$url) . self::$soConfig['hotwords_path'] . '?wt=json';
			
			$httpTransport = self::$solr->getHttpTransport();
			$httpResponse = $httpTransport->performGetRequest($url, false);
			
			if($httpResponse->getStatusCode() != 200) {
				throw new Apache_Solr_Exception($httpResponse->getStatusMessage(),$httpResponse->getStatusCode());
			}
			$httpResponse = json_decode($httpResponse->getBody());
			
			$hotList = array();
			foreach($httpResponse->hotQueryTermList as $v) {
				$hotList[] = $v->queryTerm;
			}
			
			return $hotList;
		}catch(Apache_Solr_Exception $e) {
			$this->toErrorLogs($e);
			throw new Apache_Solr_Exception($e->getMessage(),$e->getCode());
		}catch(Exception $e) {
			$this->toErrorLogs($e);
			$this->_forward('index','error',null,array('status'=>500,'error_obj'=>$e));
		}
	}
	
	//切词
	protected function getKeywords($text = '') {
		try {
			self::getSolrInstance();
		
			$url['host_port'] = self::$soConfig['server_ip'] . ":" . self::$soConfig['server_port'];
			$url['path'] = trim(self::$soConfig['server_root_path'],'/');
			
			$url = 'http://' . implode('/',$url) . '/keyword?wt=json&input=' . urlencode($text);
			
			$httpTransport = self::$solr->getHttpTransport();
			$httpResponse = $httpTransport->performGetRequest($url, false);
			
			if($httpResponse->getStatusCode() != 200) {
				throw new Exception($httpResponse->getStatusMessage(),$httpResponse->getStatusCode());
			}
			$httpResponse = json_decode($httpResponse->getBody());
			
			return $httpResponse->tag;
		}catch(Apache_Solr_Exception $e) {
			return '';
			
			$this->toErrorLogs($e);
		}catch(Exception $e) {
			$this->toErrorLogs($e);
			$this->_forward('index','error',null,array('status'=>500,'error_obj'=>$e));
		}
	}
	
	//应用list
	public function getApplistinfo(){
		$applist = $this->orm->createDAO("_users_info_app_list");
		$applist = $applist->get();
		return $applist;
	}
	
	//根据用户id获取userinfo
	public function getusernamebyuid($uid){
		$userinfo = $this->orm->createDAO("_users_info");
		$userinfo ->findUser_id($uid);
		$userinfo = $userinfo->get();
		return $userinfo;
	}
	
	/**
	 * 发送消息
	 * @param int $author_id 发送人ID
	 * @param int $user_id 接收人ID
	 * @param string $title 消息标题
	 * @param string $message 消息内容
	 * @param int $is_system 是否为系统该消息
	 * @param int $app_id 应用ID
	 * @return string
	 */
	protected function savemessage($author_id, $user_id, $title, $message, $is_system=0, $app_id=1){
		try {
			$user_infoDAO = $this->orm->createDAO('_users_info')->findUser_id($user_id);
			$user_infoDAO->notice += 1;
			$user_infoDAO->save();
			
			$user_pmDAO = $this->orm->createDAO('_users_pm');
			$user_pmDAO->author_id = $author_id;
			$user_pmDAO->user_id = $user_id;
			$user_pmDAO->title = $title;
			$user_pmDAO->message = str_replace("'", '"', $message);
			$user_pmDAO->is_system = $is_system;
			$user_pmDAO->is_new = 1;
			$user_pmDAO->app_id = $app_id;
			$user_pmDAO->datetime = time();
			return $user_pmDAO->save();
			
		}catch(Exception $e) {
			$this->toErrorLogs($e);
			$this->alert_back(addslashes($e->getMessage()));
		}
	}
	
	/*
	 * 获取用户信息
	 * @param string $uid
	 * @return $userinfo
	 */
	
	public function getuserinfoByidAction($uid){
		try {
			if(!empty($uid)){
				$userinfo = $this->orm->createDAO("_users_info");
				$userinfo ->findUser_id($uid);
				$userinfo = $userinfo->get();
				return $userinfo;
			}	
		}catch(Exception $e) {
			$this->toErrorLogs($e);
			$this->alert_back(addslashes($e->getMessage()));
		}
	}

	/*
	 * rtx提醒 --共用方法
	 * @获取发送人信息  $setuserinfo = $this->getuserinfoByidAction($author_id);
	 * @获取接收人信息  $fromuserinfo = $this->getuserinfoByidAction($user_id);
	 */
	public function SendToRtxMessageAction($setuserinfo, $fromuserinfo, $title, $message){
		try {
			if($fromuserinfo[0]['user_appname'] == 'RTX' && $fromuserinfo[0]['rtx_huida'] == 1){
				$app_list = $this->getApplistinfo();
				foreach ($app_list as $key => $value){
					if($value['wd_app_id'] == $fromuserinfo[0]['user_appid']){
						$serverip = $value['wd_app_serverip'];
						$serverport = $value['wd_app_serverport'];
					}
				}
				$xxtx = "true"; 

				$sUrl .= "http://";
				$sUrl .= $serverip.":".$serverport;
				$sUrl .= "/rtx/rtx_nodiscuz.php";

				$recename = iconv("utf-8", "gb2312", $fromuserinfo[0]['user_name']);
				$title = iconv("utf-8", "gb2312", $title);
				$message = iconv("utf-8", "gb2312", $message);
				$message = urlencode($message);
				//发送rtx消息提醒
				$re_content = @file_get_contents($sUrl."?xxtx=true&recename=".$recename."&title=".$title."&content=".$message."&delayTime=0");
			}	
		}catch(Exception $e) {
			$this->toErrorLogs($e);
			$this->alert_back(addslashes($e->getMessage()));
		}
	}
	
	/**
	 * 相关用户
	 * @param string $key 关键词
	 * @return multitype:
	 */
	protected function getRelateExpert($key){
		try {
			$users_expert_keyDAO = $this->orm->createDAO("_users_expert_key")->alias('k');
			$users_expert_keyDAO->findWd_title("%$key%", 'LIKE');
			$users_expert_keyDAO ->with_users_info(array('user_id'=>'user_id'), 'inner')->alias('u');
			$users_expert_keyDAO ->select('k.user_id, u.user_name, u.real_name, count(k.user_id) as question_count');
			$users_expert_keyDAO ->selectLimit = " group by k.user_id order by k.datetime desc limit 5";
			$users_expert_key = $users_expert_keyDAO->get();
			return $users_expert_key;
		}catch(Exception $e) {
			$this->toErrorLogs($e);
			$this->alert_back(addslashes($e->getMessage()));
		}
	}
	
	/**
	 * License相关设置
	 * @param string $key 关键词
	 * @return multitype:
	 */
	public function getLicense($counts=100){
		try {
			if($counts > 0){
				$usercountsDAO = $this->orm->createDAO("_users_info");
				$usercountsDAO = $usercountsDAO ->get();
				$countsinfo = count($usercountsDAO);
				if($countsinfo > $counts){
					$this->alert_back("您目前的用户总数为 ".$countsinfo.",已经超过license授权的用户数量 10 的上限，请联系开发商及时更新license，在使用中给您带来不便，请您谅解！");
				}
			}
		}catch (Exception $e){
			$this->toErrorLogs($e);
			$this->alert_back(addslashes($e->getMessage()));
		}
	}
}